import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons'
import { Button, DatePicker, Form, Input, Pagination, Select, Space, Switch, Table } from 'antd'
import { CheckboxValueType } from 'antd/es/checkbox/Group'
import cs from 'classnames'
import dayjs from 'dayjs'
import debounce from 'lodash/debounce'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { useContext, useEffect, useMemo, useState } from 'react'

import { Violation } from '@/api/interface'
import { EnumsRes } from '@/api/interface'
import { Enums } from '@/api/modules'
import { ViolationHome } from '@/api/modules/home'
import Add from '@/assets/svg/add.svg'
import Search from '@/assets/svg/Search-1.svg'
import { getColumns } from '@/components/EntityHome/Constants'
import EntityReply from '@/components/EntityReply'
import EntityView from '@/components/EntityView'
import EntityLayout from '@/components/LayoutEntity'
import { GlobalContext } from '@/context'
import useIsMountedRef from '@/utils/useIsMountedRef'
import useLocale from '@/utils/useLocale'

import locale from './locale'
import styles from './style/index.module.less'

const { Option } = Select
function Home() {
  const t = useLocale(locale)
  const { lang } = useContext(GlobalContext)

  const router = useRouter()

  const [tableColumns, setTableColumns] = useState<CheckboxValueType[]>([
    'refNumber',
    'createdAt',
    'violationDesc',
    'violationAdditionalDetails',
    'actions',
    'violationTypeA',
    'violationTypeB',
    'fullName',
  ])
  const options = [
    {
      label: t['columns.number'],
      value: 'refNumber',
      disabled: true,
      // width: 180,
    },
    {
      label: t['columns.created'],
      value: 'createdAt',
    },
    {
      label: t['columns.typeA'],
      value: 'violationTypeA',
    },
    {
      label: t['columns.typeB'],
      value: 'violationTypeB',
    },
    {
      label: t['columns.desc'],
      value: 'violationDesc',
    },
    {
      label: t['columns.AdditionalDetails'],
      value: 'violationAdditionalDetails',
    },
    {
      label: t['columns.createdBy'],
      value: 'fullName',
    },
    {
      label: t['columns.actions'],
      value: 'actions',
      disabled: true,
    },
  ]

  const resetTableColumns = () => {
    setTableColumns(options.map((a) => a.value))
  }

  const [viewModal, setViewModal] = useState(false)
  const [replyModal, setReplyModal] = useState(false)
  const [violation, setViolation] = useState<Partial<Violation>>({})

  const tableCallback = async (record: Partial<Violation>, type: string) => {
    setViolation(record)
    type === 'view' && setViewModal(true)
    type === 'reply' && setReplyModal(true)
  }

  const onChange = (checkedValues: CheckboxValueType[]) => {
    console.log('checked = ', checkedValues)
    setTableColumns(checkedValues)
  }

  const columns = useMemo(
    () => getColumns(t, tableCallback, tableColumns, options, lang, onChange, resetTableColumns),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [t, tableColumns]
  )

  const fetchData = async () => {
    const { pageNo, pageSize } = pagination
    setLoading(true)
    ViolationHome({ pageNo, pageSize, ...formParams })
      .then((res) => {
        if (isMountedRef.current) {
          const { count, data } = res.data
          setPatination((a) => ({ ...a, tatol: count }))
          setData(data)
          setLoading(false)
        }
      })
      .catch(() => {
        setLoading(false)
      })
  }
  const [form] = Form.useForm()
  const [data, setData] = useState([])
  const [loading, setLoading] = useState(false)
  const [formParams, setFormParams] = useState({ onlyUnreplied: false })
  const [pagination, setPatination] = useState({
    tatol: 0,
    pageNo: 1,
    pageSize: 10,
  })
  const handleSizeChange = (val: any) => {
    setPatination((a) => ({ ...a, pageSize: val }))
  }

  const handleChange = (page: any) => {
    setPatination((a) => ({ ...a, pageNo: page }))
  }
  const handleSearchChange = debounce(
    ({ q, dates, violationType }: { q: string; dates: string[]; violationType: string }) => {
      const start = dates?.length === 2 ? dayjs(dates[0]).format('YYYY-MM-DD') : ''
      const end = dates?.length === 2 ? dayjs(dates[1]).format('YYYY-MM-DD') : ''

      setFormParams((a) => ({
        ...a,
        q: q && q.trim(),
        start: start,
        end: end,
        violationTypeA: type === 'ViolationTypeAEnums' ? violationType : '',
        violationTypeB: type === 'ViolationTypeBEnums' ? violationType : '',
      }))
    },
    300
  )

  const handleKeyDown = (event: { key: string }) => {
    if (event.key === 'Enter') {
      fetchData()
    }
  }
  const handleSwitchChange = (checked: boolean) => {
    setFormParams((a) => ({ ...a, onlyUnreplied: checked }))
  }

  const [type, setType] = useState('')

  const [enums, setEnums] = useState<{ [key: string]: EnumsRes[] }>({
    ViolationTypeAEnums: [],
    ViolationTypeBEnums: [],
  })
  const getEnums = async () => {
    const enumData = await Promise.all([
      Enums({ type: 'ViolationTypeAEnums' }),
      Enums({ type: 'ViolationTypeBEnums' }),
    ])
    try {
      setEnums({
        ViolationTypeAEnums: enumData[0].data,
        ViolationTypeBEnums: enumData[1].data,
      })
    } catch (_) {}
  }
  useEffect(() => {
    getEnums()
  }, [])

  const isMountedRef = useIsMountedRef()
  useEffect(() => {
    fetchData()
  }, [pagination.pageNo, pagination.pageSize, formParams])

  // const tableColumnsFilter = () => (
  //   <>
  //     <Checkbox.Group
  //       style={{ display: 'flex', flexDirection: 'column' }}
  //       onChange={onChange}
  //       value={tableColumns}
  //       className={styles['filter-item']}
  //     >
  //       {options.map((a) => (
  //         <div className={cs('w-full h-9 flex items-center pl-4 pr-3')} key={a.value}>
  //           <Checkbox value={a.value} disabled={a.disabled}>
  //             {a.label}
  //           </Checkbox>
  //         </div>
  //       ))}
  //     </Checkbox.Group>
  //     <div className={cs('p-2 w-full flex', styles['filter-bottom'])}>
  //       <Button className={styles['reset']} onClick={resetTableColumns}>
  //         {t['form.reset']}
  //       </Button>
  //     </div>
  //   </>
  // )

  return (
    <>
      <Head>
        <title>{t.title}</title>
      </Head>
      <div className="px-[60px]">
        <div className={styles['search']}>
          <div className={cs('flex justify-between pt-11 pb-4 items-end')}>
            <span className={cs('text-[16202D] text-[30px] font-bold ')}>{t['page.title']}</span>

            <Button
              type="primary"
              className={cs(styles['add'])}
              onClick={() => router.push('/entityForm')}
            >
              <Add className={cs(' w-4 h-4 mx-1', styles['icon'])} />
              <span className="Roboto text-[14px] font-bold">{t['form.add']}</span>
            </Button>
          </div>

          {/* 搜索区域 */}
          <div className={cs('flex pb-4 justify-between')}>
            <Form
              layout="inline"
              form={form}
              onValuesChange={handleSearchChange}
              className={cs(styles['from'])}
            >
              <Form.Item name="q" className={cs(styles['from-item'])}>
                <Input
                  allowClear
                  placeholder={t['form.search.placeholder']}
                  onKeyDown={handleKeyDown}
                  suffix={
                    <>
                      <Search
                        className={cs(styles['search-icon'], 'cursor-pointer')}
                        onClick={fetchData}
                      />
                    </>
                  }
                />
              </Form.Item>

              <Space.Compact className={cs(styles['select-group'], styles['from-item'])}>
                <Select
                  className={cs(styles['select-group-label'])}
                  placeholder={t['form.type.placeholder']}
                  allowClear
                  onChange={(e) => {
                    setType(e)
                    form.setFieldsValue({ violationType: undefined })
                    setFormParams((a) => ({
                      ...a,
                      violationTypeA: '',
                      violationTypeB: '',
                    }))
                  }}
                  suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                >
                  <Option value="ViolationTypeAEnums">{t['form.type.typeA']}</Option>
                  <Option value="ViolationTypeBEnums">{t['form.type.typeB']}</Option>
                </Select>
                <Form.Item name="violationType" className={cs(styles['from-item'])}>
                  <Select
                    className={cs(styles['select-group-value'])}
                    placeholder={t['form.select.placeholder']}
                    allowClear
                    suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                  >
                    {type &&
                      enums[type].map((option, index) => (
                        <Option key={index} value={option.key}>
                          {option.value[lang === 'en-US' ? 'en' : 'ar']}
                        </Option>
                      ))}
                  </Select>
                </Form.Item>
              </Space.Compact>

              {/* <Form.Item name="q" className={cs(styles['from-item'])}>
                <Input
                  allowClear
                  placeholder={t['form.search.placeholder']}
                  onKeyDown={handleKeyDown}
                  suffix={
                    <>
                      <Search
                        className={cs(styles['search-icon'], 'cursor-pointer')}
                        onClick={fetchData}
                      />
                    </>
                  }
                />
              </Form.Item> */}
              <Form.Item name="dates" className={cs(styles['from-item'])}>
                <DatePicker.RangePicker
                  format="YYYY-MM-DD"
                  placeholder={[
                    t['form.createdDate.start.placeholder'],
                    t['form.createdDate.end.placeholder'],
                  ]}
                  disabledDate={(date: string | number | Date | dayjs.Dayjs | null | undefined) =>
                    dayjs(date).isAfter(dayjs())
                  }
                  suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                />
              </Form.Item>
            </Form>
            <div className={cs(styles['switch'], 'flex items-center')}>
              <Switch
                className={cs(styles['switch-switch'])}
                onChange={handleSwitchChange}
                checked={formParams.onlyUnreplied}
              />
              <span className={cs('Roboto text-[14px] font-bold')}>{t['form.switch']}</span>
            </div>
          </div>
        </div>
        {/* 表单 */}
        <div className={cs(styles['table'], 'relative')}>
          {/* <div
            className={cs('absolute top-0 z-50 p-[16px]', lang === 'en-US' ? 'right-0' : 'left-0')}
          >
            <Popover placement="bottom" arrow={false} content={tableColumnsFilter} trigger="hover">
              <div className={cs(styles['filter'])}>
                <Group9 className={cs(' w-6 h-6', styles['icon'])} />
              </div>
            </Popover>
          </div> */}
          <Table
            dataSource={data}
            rowKey="id"
            columns={columns}
            pagination={false}
            loading={loading}
          />
        </div>

        {/* 翻页 */}
        <div className={cs('flex items-center justify-between h-16', styles['pagination'])}>
          <div>
            <span className={cs('text-[#B9B9B9] text-[14px] font-normal')}>
              {pagination.tatol} {t['pagination.tatol']}
            </span>
            <Select
              className="ltr"
              defaultValue={pagination.pageSize}
              style={{ width: 110, height: 44, marginLeft: 20, marginRight: 20 }}
              onChange={handleSizeChange}
              suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
            >
              {[10, 20, 50, 100].map((a) => (
                <Select.Option
                  className={cs('ltr', lang === 'en-US' ? '' : 'Cairo')}
                  value={a}
                  key={a}
                >
                  {`${a} ${t['pagination.page']}`}
                </Select.Option>
              ))}
            </Select>
          </div>

          <Pagination
            total={pagination.tatol}
            current={pagination.pageNo}
            pageSize={pagination.pageSize}
            showSizeChanger={false}
            showQuickJumper
            onChange={handleChange}
          />
        </div>
      </div>

      <EntityView violation={violation} isModalOpen={viewModal} setIsModalOpen={setViewModal} />

      <EntityReply
        violation={violation}
        isModalOpen={replyModal}
        setIsModalOpen={setReplyModal}
        refresh={fetchData}
      />
    </>
  )
}

export default Home

Home.getLayout = function getLayout(page: React.ReactNode) {
  return <EntityLayout>{page}</EntityLayout>
}
